import React from 'react';
import { Table, ConfigProvider, Button, Space, Switch, Popover, Modal, Form, Input, Select, Radio, Upload, message, Tag } from 'antd';
import { PlayCircleOutlined, VerticalAlignBottomOutlined, RestOutlined, EditOutlined, UploadOutlined, PlusSquareOutlined } from '@ant-design/icons';
import "./flContent.css"


import axios from '../../utils/myAxios';
import moment from 'moment';
import qs from 'qs'





const { TextArea } = Input;


// const upprops = {
//     name: 'file',
//     action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
//     headers: {
//         authorization: 'Access-Control-Allow-Origin',
//     },
//     onChange(info) {
//         console.log(info);
//         if (info.file.status !== 'uploading') {
//             console.log(info.file, info.fileList);
//         }
//         if (info.file.status === 'done') {
//             message.success(`${info.file.name} file uploaded successfully`);
//         } else if (info.file.status === 'error') {
//             message.error(`${info.file.name} file upload failed.`);
//         }
//     },
// };





class Flcontent extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            visible: false,
            visible2: false,
            display: '',
            key: '',
            value: 1,
            count: '',
            
            data: [
                {
                    key: '5',
                    sort: '数据导出',
                    fileName: '客户列表-20220330-1658.img',
                    remark: '这是备注',
                    address: 'https://img2.baidu.com/it/u=1814268193,3619863984&fm=253&fmt=auto&app=138&f=JPEG?w=632&h=500',
                    dowload: 0,
                    share: 0,
                    publisher: '超级管理员',
                    time: '2022/3/30 16:58:47',
                },
                {
                    key: '6',
                    sort: '导出存档',
                    fileName: '客户列表-20220330-1658.xls',
                    remark: '这是备注这是备注这是备注这是备注这是备注这是备注这是备注这是备注这是备注这是备注这是备注这是备注这是备注这是备注这是备注',
                    address: 'https://demo.126e.com/upload/files/2022-4/202204060926579275.doc',
                    dowload: 1,
                    share: 1,
                    publisher: '管理员',
                    time: '2022/3/30 16:58:47',
                }

            ],
            columns: [
                {
                    title: '分类',
                    dataIndex: 'fileclass',

                    render: (fileclass) => {
                        return fileclass.filename
                    }
                },
                {
                    title: '文件名',
                    dataIndex: 'fileaddresses',
                    render: (fileaddresses) => {
                        return fileaddresses[0].filename
                    }
                },
                {
                    title: '备注',
                    dataIndex: 'remark',
                    width: '150px',
                    render: (remark) => {


                        if (remark.length > 7) {
                            return (<div className='scrolls'  >{remark}</div>)
                        } else {
                            return (<div>{remark}</div>)
                        }

                    }



                },
                {
                    title: '下载',
                    dataIndex: 'fileaddresses',
                    width: '80px',
                    render: (fileaddresses) => {
                        // console.log(fileaddresses[0].filcls);
                        return (
                            <div>
                                {
                                    fileaddresses[0].filcls ? <Button onClick={this.showImage.bind(this, fileaddresses[0].fileaddress)} ><VerticalAlignBottomOutlined />下载  </Button>
                                        : <Button onClick={this.showImage.bind(this, fileaddresses[0].fileaddress)}><PlayCircleOutlined />
                                            查看</Button>
                                }


                            </div>

                        )

                    }
                },
                {
                    title: '共享',
                    dataIndex: 'share',

                    render: (share) => {
                        return (
                            <Space>
                                {share ? <Switch defaultChecked /> : <Switch />}

                            </Space>

                        )
                    }
                },
                {
                    title: '发布人',
                    dataIndex: 'employee',
                    render: (employee) => {
                        return employee.name


                    }
                },
                {
                    title: '时间',
                    dataIndex: 'time',
                    render: (time) => {
                        return moment(time).format("YYYY-MM-DD HH:mm:ss ")

                    }
                },
                {
                    title: '管理',
                    dataIndex: 'management',
                    render: (txt, key) => {
                        return (
                            <Space>
                                <EditOutlined style={{ color: 'blue' }} onClick={this.showModal.bind(this, key)}  >
                                </EditOutlined>

                                <Popover
                                    content={<Button onClick={this.delete.bind(this, key)} > 确认删除 </Button>}
                                    // title="Title"
                                    trigger="hover"
                                // visible={this.state.a}
                                // onVisibleChange={this.handleVisibleChange}
                                > <RestOutlined style={{ color: 'red' }} /></Popover>
                            </Space>

                        )
                    }
                },

            ],
            // 文件类型
            fileClass: [],
            // 模态框值
            defValue: "",
            defShare: '',
            defRemark: '',
            changeClassValue: '',
            changeClassName: '',
            currentpage: 1,
            currentcount: 5,
            tablelist: '',
            formatFile: '',
            fcid: '',
            fileaddressId: ''

        };


        this.getAll()
        this.getClassName()

    }

    componentWillReceiveProps(props) {

        const display = props.setdisplayvalue;
        // console.log('display', display)
        this.setState({ visible: display });

    }

    getAll = () => {
        axios({
            url: '/document/selectAll',
            method: 'get',
            params: {
                'currentPage': this.state.currentpage,
                'page': this.state.currentcount
            },


        }).then(res => {
            console.log(res);
            let a = res.data.data.data
            console.log(a);
            this.setState({
                count: res.data.data.countAll,
                tablelist: a
            })

    
        })
    }

    getClassName = () => {
        axios({
            url: '/document/selectClassname',
            method: 'get',



        }).then(res => {
            let a = res.data.data
            console.log(res.data.data);
            this.setState({
                fileClass: a
            })

        })
    }



    // 上传文件
    onFinish = (values) => {
        let _this=this
        // console.log('Success:', values);
 
        console.log(this.state.key,this.state.fcid,this.state.fileaddressId,values.remark);
        if (this.state.key != '') {
            axios({
                url:'/document/upDateDocument',
                method: 'POST',
                params: {
                    docuemntId: this.state.key,
                    fcid: this.state.fcid,
                    // file: this.state.formatFile,
                    fileAddressId: this.state.fileaddressId,
                    remark: values.remark,
                    share: values.share
                }
              
            }).then(res => {
                this.getAll()
              
                
            })
        } else {
            axios({
                url: '/document/insertdocument',
                method: 'post',
                params: {
                    empid: 2,
                    fcid: values.fcid,
                    
                    // file: this.state.formatFile,
                    remark: values.remark,
                    share: values.share
                }


            }).then(res => {


            })
        }



    };
    onFinishFailed = (errorInfo) => {
        console.log('Failed:', errorInfo);
    };


    // 选项值
    onFinishs = (values) => {
        let names = []
        this.state.fileClass.forEach(item => {
            names.push(item.filename)
        })
        console.log(values);
        //    判断是否存在选项值
        console.log(names);
        let judgement = names.findIndex((item => {
            return item == values.newChoice
        }))
        // console.log(judgement);
        console.log(this.state.changeClassName);
        if (judgement == -1 && this.state.changeClassName == "") {
            // 新增选项
            axios({
                url: '/document/insertFileClass',
                method: 'post',
                params: {
                    className: values.newChoice
                }
            }).then(res => {
                this.getClassName()
            })
        } else {
            // 修改选项
            axios({
                url: '/document/upDateFileClass',
                method: 'post',
                params: {
                    fileName: values.newChoice,
                    id: this.state.changeClassValue
                }
            }).then(res => {
                this.getClassName()
            })

        }



    };
    onFinishsFailed = (errorInfo) => {
        console.log('Failed:', errorInfo);

    };

    delete = (key) => {
        console.log(key.id);
        axios({
            url: '/document/delDocument',
            method: 'post',
            params: {
                id: key.id
            }
        }).then(res => {
            this.getAll()

        })
    }

    // 打开修改文件模态框
    showModal = (key) => {
        console.log(key);

        console.log(key.fileaddresses[0].id);

        this.setState({
            visible: !this.state.visible,
            key: key.id,
            fcid: key.fileclassId,
            fileaddressId: key.fileaddresses[0].id,
            defValue: key.fileclass.filename,
            defShare: key.share,
            defRemark: key.remark,

        }, () => {
            // console.log(this.state.visible);
        });



    };
    hideModal = () => {
        this.setState({
            visible: !this.state.visible,
        });
        this.props.setdisplay()
    };

    // 打开选项值模态框
    showModal2 = () => {
        // console.log(this.state.key);

        this.getClassName()
        this.setState({
            visible2: !this.state.visible2,

        }, () => {
            // console.log(this.state.visible2);
        });
    }
    hideModal2 = () => {
        this.setState({
            visible2: !this.state.visible2,
        });

    }

    // 显示图片，下载文件
    showImage = (key) => {

        window.open(key)

    }

    // 修改选项值
    changeClass = (item) => {
        console.log(item);
        this.setState({
            changeClassValue: item.id,
            changeClassName: item.filename,
        });
    }

    // 删除选项值
    CloseTag = (item) => {
        console.log(item);
        axios({
            url: '/document/delFileClass',
            method: 'post',
            params: {

                id: item.id
            }
        }).then(res => {
            this.getClassName()
        })
    }
    // 获取单选框
    onChange = e => {
        console.log('radio checked', e.target.value);
        this.setState({
            value: e.target.value,
        });
    };

    changePage = (key) => {
        console.log(key);
        this.setState({
            currentpage: key
        }, () => {
            this.getAll()
        })

    }
    customRequest = async (option) => {
        //    console.log(option);
        let formData = new FormData();


        formData.append('file', option.file)



        this.setState({
            formatFile: formData
        })


    }
    // beforeUpload(file, fileList) {
    //     console.log('fileList', file)
    //     this.setState({
    //         formatFile: file
    //     })
    // }

    render() {

        return (
            <div>
                <Table dataSource={this.state.tablelist} columns={this.state.columns}

                    pagination={{
                        showSizeChanger: true,
                        showQuickJumper: true,
                        defaultPageSize: 5,
                        onChange: (key) => this.changePage(key),

                        total: this.state.count,
                        showTotal: (total, range) => ` 共 ${total} 条`,
                        pageSizeOptions: ['5', '10', '15'],
                        defaultCurrent: 1,

                    }}
                    rowKey={(item) => item.id}


                >


                </Table>
                {/* 一阶模态框 */}
                <Modal
                    title="文件处理"
                    visible={this.state.visible}
                    destroyOnClose={true}
                    // onOk={this.hideModal}
                    onCancel={this.hideModal}
                    footer={
                        [] // 设置footer为空，去掉 取消 确定默认按钮
                    }

                >
                    <Form
                        name="file"
                        labelCol={{ span: 8 }}
                        wrapperCol={{ span: 16 }}
                        initialValues={{ remember: true }}
                        onFinish={this.onFinish}
                        onFinishFailed={this.onFinishFailed}
                        autoComplete="off"
                    >
                        <Form.Item
                            label="文件分类"
                        // rules={[{ required: true, message: '请选择类型' }]}
                        >
                            <Space>
                                <Form.Item name="fcid">
                                    <Select placeholder="请选择" style={{ width: '140px' }} defaultValue={this.state.defValue}>
                                        {
                                            this.state.fileClass.map((item, index) =>
                                                <Select.Option key={index} value={item.id}  >{item.filename}</Select.Option>
                                            )
                                        }



                                    </Select>
                                </Form.Item>
                                <Form.Item>
                                    <Button onClick={this.showModal2}>
                                        <PlusSquareOutlined></PlusSquareOutlined>
                                        新增
                                    </Button>
                                </Form.Item>
                            </Space>

                        </Form.Item>

                        <Form.Item
                            label="是否共享"
                            name="share"
                        >
                            <Radio.Group onChange={this.onChange} Value={this.state.defShare}>
                                <Radio value={1}>是
                                </Radio>
                                <Radio value={0}>否
                                </Radio>
                            </Radio.Group>
                        </Form.Item>

                        <Form.Item label="文件上传" name="Upload" valuePropName="Upload" wrapperCol={{ offset: 0, span: 16 }}>
                            <Upload
                                customRequest={this.customRequest}
                            // beforeUpload={this.beforeUpload}

                            >
                                <Button icon={<UploadOutlined />}>Upload</Button>
                            </Upload>
                            {/* <Input type="file" onChange={this.send} /> */}

                        </Form.Item>
                        <Form.Item label="备注" name="remark" wrapperCol={{ offset: 0, span: 16 }}>
                            <TextArea rows={4} defaultValue={this.state.defRemark} />
                        </Form.Item>

                        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                            <Button type="primary" htmlType="submit">
                                提交
                            </Button>
                        </Form.Item>
                    </Form>
                </Modal>

                {/* 二阶模态框 */}
                <Modal
                    zIndex='1001'
                    title="自定义选项值"
                    visible={this.state.visible2}
                    footer={
                        [] // 设置footer为空，去掉 取消 确定默认按钮
                    }
                    onCancel={this.hideModal2}

                >
                    <Form
                        name="choice"
                        labelCol={{ span: 8 }}
                        wrapperCol={{ span: 16 }}
                        initialValues={{ remember: true }}
                        onFinish={this.onFinishs}
                        onFinishFailed={this.onFinishsFailed}
                        autoComplete="off"
                    >




                        <Form.Item label="新增选项值" name="newChoice">
                            <Input key={this.state.changeClassValue} defaultValue={this.state.changeClassName}></Input>

                        </Form.Item>


                        <Form.Item label="已有的选项值" name="Choices">
                            {
                                this.state.fileClass.map((item, index) =>
                                    <Tag key={index} closable onClose={this.CloseTag.bind(this, item)} onClick={this.changeClass.bind(this, item)} value={item.id} color="blue">{item.filename}</Tag>
                                )
                            }




                        </Form.Item>

                        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                            <Button type="primary" htmlType="submit">
                                提交
                            </Button>
                        </Form.Item>
                    </Form>

                </Modal>
            </div >
        )
    }
}


export default Flcontent